<!-- 工艺路线显示页面 -->
<template>
    <div class="craft-route">
        <el-form style="margin-bottom: 16px;">
            <el-button type="danger" @click="handleBatchDelete" :disabled="!multipleSelection.length">
                <el-icon><Delete /></el-icon> 批量删除
            </el-button>
            <el-button type="success" @click="toOpen(null)" style="margin-left: 10px;">
                <el-icon><Plus /></el-icon> 添加
            </el-button>
        </el-form>
        <el-table
        :data="tableData"
        border
        style="width: 100%"
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="工艺线路" />
            <el-table-column prop="desc" label="流程描述" />
            <el-table-column prop="process" label="流程时序过程" width="500" />
            <el-table-column label="操作" width="220">
                <template #default="scope">
                <el-button size="small" type="primary" @click="toOpen(scope.row)"><el-icon><EditPen /></el-icon>编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row)"><el-icon><Delete /></el-icon>删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-dialog v-model="dialogFormVisible" title="工艺路线设置" width="700" >
            <el-form
                ref="ruleFormRef"
                style="max-width: 600px;align-content: center;margin: auto;"
                :model="ruleForm"
                :rules="rules"
                label-width="auto"
            >
                <el-form-item label="工艺线路" prop="name">
                    <el-input v-model="ruleForm.name" />
                </el-form-item>
                
                <el-form-item label="流程描述" prop="desc">
                    <el-input v-model="ruleForm.desc" type="textarea" />
                </el-form-item>

                <el-form-item label="流程时序">
                    <el-input v-model="ruleForm.process" type="textarea" />
                </el-form-item>

                <el-divider>流程与工序关系</el-divider>
                
                <el-row>
                    <el-col :span="10">
                        <el-checkbox v-model="allProcessesSelected" @change="handleCheckAllProcesses">全部工序</el-checkbox>
                        <div style="height: 300px; overflow-y: auto; border: 1px solid #dcdfe6;">
                            <el-checkbox-group v-model="selectedAllProcesses">
                                <div v-for="item in allProcesses" :key="item.code">
                                    <el-checkbox :label="item.code">{{ item.name }}</el-checkbox>
                                </div>
                            </el-checkbox-group>
                        </div>
                    </el-col>
                    <el-col :span="4" style="display: flex; justify-content: center; align-items: center; flex-direction: column;">
                        <el-button type="danger" style="margin-bottom: 10px;" @click="addToCurrentFlow" :disabled="!selectedAllProcesses.length">
                            <el-icon> >> </el-icon>
                        </el-button>
                        <el-button type="warning" @click="removeFromCurrentFlow" :disabled="!selectedCurrentProcesses.length">
                            <el-icon> << </el-icon>
                        </el-button>
                    </el-col>
                    <el-col :span="10">
                        <el-checkbox v-model="currentFlowSelected" @change="handleCheckCurrentFlow">当前Flow下工序</el-checkbox>
                        <div style="height: 300px; overflow-y: auto; border: 1px solid #dcdfe6; display: flex; justify-content: center; align-items: center;" v-if="!ruleForm.currentProcesses.length">
                            无数据
                        </div>
                        <div style="height: 300px; overflow-y: auto; border: 1px solid #dcdfe6;" v-else>
                            <el-checkbox-group v-model="selectedCurrentProcesses">
                                <div v-for="item in ruleForm.currentProcesses" :key="item.code">
                                    <el-checkbox :label="item.code">{{ item.name }}</el-checkbox>
                                </div>
                            </el-checkbox-group>
                        </div>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false" style="margin-bottom: 5px;">取消</el-button>
                <el-button type="primary" v-show="IsShow" @click="handleAdd" style="margin-bottom: 5px;margin-right: 10px;">添加</el-button>
                <el-button type="primary" v-show="!IsShow" @click="handleEdit" style="margin-bottom: 5px;margin-right: 10px;">编辑</el-button>
            </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Plus, EditPen, ArrowRight, ArrowLeft } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'

interface Process {
    code: string;
    name: string;
}

interface CraftRoute {
  id: number
  name: string
  desc: string
  process: string
  currentProcesses?: Process[]
}

const tableData = ref<CraftRoute[]>([
  { id: 1, name: '工艺线路', desc: '测速传感器', process: '压接端子->电焊阻->点胶->焊接->绕线->加固' },
  { id: 2, name: '测速传感器', desc: '测速传感器', process: '压接端子->电焊阻->点胶->焊接->绕线->测耐压' },
  { id: 3, name: '磁阻传感器', desc: '磁阻传感器', process: '压接端子->电焊阻->点胶->焊接->绕线->测耐压' },
  { id: 4, name: '压力传感器', desc: '压力传感器', process: '压接端子->电焊阻->点胶->焊接->绕线->测耐压' },
  { id: 5, name: '12', desc: '12', process: '打毛刺->焊接->加酸工序->焊接' },
  { id: 6, name: '妇女', desc: '二', process: '封胶工序->加酸工序' },
  { id: 7, name: '的方式', desc: '人太多', process: '包装工序->集成测试工序' },
  { id: 8, name: '地方', desc: '地认识到', process: '压铸->打毛刺' },
  { id: 9, name: '更应该', desc: '还敢不敢', process: '压铸->打毛刺' },
])

// 所有可选工序列表
const allProcesses = ref<Process[]>([
  { code: 'ASY-01', name: 'ASY-01' },
  { code: 'TST-02', name: 'TST-02' },
  { code: 'APK-01', name: 'APK-01' },
  { code: 'TST-01', name: 'TST-01' },
  { code: 'HJ-01', name: 'HJ-01' },
  { code: 'FJ-01', name: 'FJ-01' },
  { code: 'JS-01', name: 'JS-01' },
  { code: 'QX-01', name: 'QX-01' },
  { code: 'RK-01', name: 'RK-01' },
  { code: '上料', name: '上料' },
])

const multipleSelection = ref<CraftRoute[]>([])
const dialogFormVisible = ref(false)
const IsShow = ref(false)
const ruleFormRef = ref<FormInstance>()
const allProcessesSelected = ref(false)
const currentFlowSelected = ref(false)
const selectedAllProcesses = ref<string[]>([])
const selectedCurrentProcesses = ref<string[]>([])

const ruleForm = reactive<{
  id?: number,
  name: string,
  desc: string,
  process: string,
  currentProcesses: Process[]
}>({
  name: '',
  desc: '',
  process: '',
  currentProcesses: [],
})

const rules = reactive<FormRules>({
  name: [
    { required: true, message: '必填项不能为空', trigger: 'blur' },
  ],
  desc: [
    { required: true, message: '必填项不能为空', trigger: 'blur' },
  ],
})

function handleSelectionChange(val: CraftRoute[]) {
  multipleSelection.value = val
}

function handleBatchDelete() {
  ElMessageBox.confirm('确定要批量删除选中的工艺路线吗？', '提示', {
    type: 'warning'
  }).then(() => {
    const ids = multipleSelection.value.map(item => item.id)
    tableData.value = tableData.value.filter(item => !ids.includes(item.id))
    multipleSelection.value = []
    ElMessage.success('删除成功')
  })
}

function handleCheckAllProcesses(val: boolean) {
  if (val) {
    selectedAllProcesses.value = allProcesses.value.map(item => item.code)
  } else {
    selectedAllProcesses.value = []
  }
}

function handleCheckCurrentFlow(val: boolean) {
  if (val) {
    selectedCurrentProcesses.value = ruleForm.currentProcesses.map(item => item.code)
  } else {
    selectedCurrentProcesses.value = []
  }
}

// 添加到当前流程
function addToCurrentFlow() {
  if (selectedAllProcesses.value.length === 0) {
    ElMessage.warning('请先选择要添加的工序')
    return
  }
  
  selectedAllProcesses.value.forEach(code => {
    const process = allProcesses.value.find(item => item.code === code)
    if (process && !ruleForm.currentProcesses.some(item => item.code === code)) {
      ruleForm.currentProcesses.push({ ...process })
    }
  })
  
  selectedAllProcesses.value = []
  allProcessesSelected.value = false
}

// 从当前流程移除
function removeFromCurrentFlow() {
  if (selectedCurrentProcesses.value.length === 0) {
    ElMessage.warning('请先选择要移除的工序')
    return
  }
  
  ruleForm.currentProcesses = ruleForm.currentProcesses.filter(
    item => !selectedCurrentProcesses.value.includes(item.code)
  )
  
  selectedCurrentProcesses.value = []
  currentFlowSelected.value = false
}

const toOpen = (row: CraftRoute | null) => {
  // 设置对话框标题
  dialogFormVisible.value = true
  
  if (row === null) {
    IsShow.value = true // 添加新工艺路线
    // 清空表单
    ruleForm.name = ''
    ruleForm.desc = ''
    ruleForm.process = ''
    ruleForm.currentProcesses = []
    selectedAllProcesses.value = []
    selectedCurrentProcesses.value = []
  } 
  else {
    IsShow.value = false // 编辑现有工艺路线
    // 填充表单
    ruleForm.id = row.id
    ruleForm.name = row.name
    ruleForm.desc = row.desc
    ruleForm.process = row.process
    ruleForm.currentProcesses = row.currentProcesses || []
    selectedAllProcesses.value = []
    selectedCurrentProcesses.value = []
  }
}

function handleAdd() {
  ruleFormRef.value?.validate((valid) => {
    if (valid) {
      // 生成新ID (简单方法，实际应该从后端获取)
      const newId = Math.max(...tableData.value.map(item => item.id)) + 1
      
      // 添加新记录
      tableData.value.push({
        id: newId,
        name: ruleForm.name,
        desc: ruleForm.desc,
        process: ruleForm.process,
        currentProcesses: [...ruleForm.currentProcesses]
      })
      
      dialogFormVisible.value = false
      ElMessage.success('添加成功')
    }
  })
}

function handleEdit() {
  ruleFormRef.value?.validate((valid) => {
    if (valid && ruleForm.id !== undefined) {
      // 查找并更新记录
      const index = tableData.value.findIndex(item => item.id === ruleForm.id)
      if (index !== -1) {
        tableData.value[index] = {
          id: ruleForm.id,
          name: ruleForm.name,
          desc: ruleForm.desc,
          process: ruleForm.process,
          currentProcesses: [...ruleForm.currentProcesses]
        }
        
        dialogFormVisible.value = false
        ElMessage.success('更新成功')
      }
    }
  })
}

function handleDelete(row: CraftRoute) {
  ElMessageBox.confirm(`确定要删除【${row.name}】吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    tableData.value = tableData.value.filter(item => item.id !== row.id)
    ElMessage.success('删除成功')
  })
}
</script>

<style scoped>
.el-form {
  margin-bottom: 16px;
  margin-top: 16px;
}
.craft-route {
}



</style>